package com.example.orderfood2.Repository;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;

import com.example.orderfood2.entity.SchoolNew;

import java.util.ArrayList;
import java.util.List;

public class SchoolNewRepository extends BaseRepository {
    public SchoolNewRepository(Context context) {
        super(context);
    }

    //    添加校园新闻
    public void addSchoolNew(String title, String content) {
        open();
        String sql = "INSERT INTO school_new (title, content) VALUES (?, ?)";
        Object[] args = {title, content};
        database.execSQL(sql, args);
        close();
    }

    //    返回数据库中倒数第6个到倒数第2个的校园新闻
    public List<SchoolNew> querySchoolNews() {
        open();
        String sql = "SELECT title, content FROM school_new ORDER BY id DESC LIMIT 5 OFFSET 1";
        Cursor cursor = database.rawQuery(sql, null);
        List<SchoolNew> schoolNews = new ArrayList<>();
        while (cursor.moveToNext()) {
            @SuppressLint("Range") SchoolNew object = new SchoolNew(
                    cursor.getString(cursor.getColumnIndex("title")),
                    cursor.getString(cursor.getColumnIndex("content"))
            );
            schoolNews.add(object);
        }
        cursor.close();
        close();
        return schoolNews;
    }

    //    根据新闻名查询新闻
    @SuppressLint("Range")
    public SchoolNew querySchoolNewByTitle(String title) {
        open();
        String sql = "SELECT title, content FROM school_new WHERE title = ?";
        String[] args = {title};
        Cursor cursor = database.rawQuery(sql, args);
        SchoolNew schoolNew = null;
        if (cursor.moveToNext()) {
            schoolNew = new SchoolNew(
                    cursor.getString(cursor.getColumnIndex("title")),
                    cursor.getString(cursor.getColumnIndex("content"))
            );
        }
        return schoolNew;
    }

    //返回数据库中最新的新闻
    @SuppressLint("Range")
    public SchoolNew queryLatestSchoolNew() {
        open();
        String sql = "SELECT title, content FROM school_new ORDER BY id DESC LIMIT 1";
        SchoolNew schoolNew = null;
        Cursor cursor = database.rawQuery(sql, null);
        if (cursor != null && cursor.moveToFirst()) {
            schoolNew = new SchoolNew(
                    cursor.getString(cursor.getColumnIndex("title")),
                    cursor.getString(cursor.getColumnIndex("content"))
            );
        }
        if (cursor != null) {
            cursor.close();
        }
        close();
        return schoolNew;
    }
}
